package com.moco.launcher.play;

/*import io.vov.vitamio.MediaFormat;
 import io.vov.vitamio.MediaPlayer;
 import io.vov.vitamio.Vitamio;
 import io.vov.vitamio.MediaPlayer.OnBufferingUpdateListener;
 import io.vov.vitamio.MediaPlayer.OnCompletionListener;
 import io.vov.vitamio.MediaPlayer.OnErrorListener;
 import io.vov.vitamio.MediaPlayer.OnInfoListener;
 import io.vov.vitamio.MediaPlayer.OnKeyDownListener;
 import io.vov.vitamio.MediaPlayer.OnLayoutListener;
 import io.vov.vitamio.MediaPlayer.OnPreparedListener;
 import io.vov.vitamio.MediaPlayer.OnSeekCompleteListener;
 import io.vov.vitamio.MediaPlayer.OnTimedTextListener;
 import io.vov.vitamio.MediaPlayer.TrackInfo;*/

import java.util.Map;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnInfoListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.media.MediaPlayer.OnTimedTextListener;
import android.media.TimedText;
import android.net.Uri;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.moco.launcher.bean.MOCO_CONSTANTS;
import com.moco.launcher.play.MediaController.MediaPlayerControl;
import com.oazon.common.Logger;
import com.oazon.common.util.RequestManager;
import com.oazon.moco.playlist.db.ServiceMsgDao;
import com.oazon.sonos.core.SonosControler;
import com.oazon.sonos.listener.SonosListener;

public class AndroidMusicPlayer implements MediaPlayerControl {

	private static final String TAG = "VitamioPlayer";
	private volatile static AndroidMusicPlayer instance;
	private static Context mContext = null;
    public String theMp3Path;
	/** Returns singleton class instance */
	public static AndroidMusicPlayer getInstance() {
		if (instance == null) {
			
			synchronized (AndroidMusicPlayer.class) {
				if (instance == null) {
					instance = new AndroidMusicPlayer();
				}
			}
		}
		return instance;
	}

	public void init(Context context) {
		mContext = context;
	}

	private OnCompletionListener mOnCompletionListener;
	private OnPreparedListener mOnPreparedListener;
	private OnErrorListener mOnErrorListener;
	private OnSeekCompleteListener mOnSeekCompleteListener;
	private OnTimedTextListener mOnTimedTextListener;
	private OnInfoListener mOnInfoListener;
	private OnBufferingUpdateListener mOnBufferingUpdateListener;

	private MediaPlayer mMediaPlayer = null;
	private Uri mUri;
	private long mDuration;
	private int mCurrentBufferPercentage;
	private long mSeekWhenPrepared; // recording the seek position while

	private int mCurrentState = STATE_IDLE;
	private int mTargetState = STATE_IDLE;
	private static final int STATE_ERROR = -1;
	private static final int STATE_IDLE = 0;
	private static final int STATE_PREPARING = 1;
	private static final int STATE_PREPARED = 2;
	private static final int STATE_PLAYING = 3;
	private static final int STATE_PAUSED = 4;
	private static final int STATE_PLAYBACK_COMPLETED = 5;
	private static final int STATE_SUSPEND = 6;
	private static final int STATE_RESUME = 7;
	private static final int STATE_SUSPEND_UNSUPPORTED = 8;
	private boolean mHardwareDecoder = false;
	private Map<String, String> mHeaders;
	private int mBufSize;

	OnPreparedListener mPreparedListener = new OnPreparedListener() {
		@Override
		public void onPrepared(MediaPlayer mp) {
			mCurrentState = STATE_PREPARED;
			if (mOnPreparedListener != null) {
				mOnPreparedListener.onPrepared(mp);
			}
		}
	};

	OnCompletionListener mCompletionListener = new OnCompletionListener() {

		@Override
		public void onCompletion(MediaPlayer mp) {
			// TODO Auto-generated method stub
			mCurrentState = STATE_PLAYBACK_COMPLETED;
			mTargetState = STATE_PLAYBACK_COMPLETED;
			if (mOnCompletionListener != null) {
				mOnCompletionListener.onCompletion(mp);
			}
		}

	};

	OnErrorListener mErrorListener = new OnErrorListener() {

		@Override
		public boolean onError(MediaPlayer mp, int what, int extra) {
			// TODO Auto-generated method stub
			Log.d(TAG, "Error: %d, %d" + what + extra);
			mCurrentState = STATE_ERROR;
			mTargetState = STATE_ERROR;
			if (mOnErrorListener != null) {
				mOnErrorListener.onError(mp, what, extra);
			}
			return false;
		}

	};

	OnBufferingUpdateListener mBufferingUpdateListener = new OnBufferingUpdateListener() {

		@Override
		public void onBufferingUpdate(MediaPlayer mp, int percent) {
			// TODO Auto-generated method stub
			mCurrentBufferPercentage = percent;
			if (mOnBufferingUpdateListener != null) {
				mOnBufferingUpdateListener.onBufferingUpdate(mp, percent);
			}
		}

	};

	OnInfoListener mInfoListener = new OnInfoListener() {

		@Override
		public boolean onInfo(MediaPlayer mp, int what, int extra) {
			// TODO Auto-generated method stub
			Log.d(TAG, "what: " + what);
			if (mOnInfoListener != null) {
				mOnInfoListener.onInfo(mp, what, extra);
			}
			return true;
		}

	};

	OnSeekCompleteListener mSeekCompleteListener = new OnSeekCompleteListener() {

		@Override
		public void onSeekComplete(MediaPlayer mp) {
			// TODO Auto-generated method stub
			if (mOnSeekCompleteListener != null) {
				mOnSeekCompleteListener.onSeekComplete(mp);
			}
		}

	};

	@SuppressLint("NewApi")
	OnTimedTextListener mTimedTextListener = new OnTimedTextListener() {

		@SuppressLint("NewApi")
		@Override
		public void onTimedText(MediaPlayer mp, TimedText text) {
			if (mOnTimedTextListener != null) {
				mOnTimedTextListener.onTimedText(mp, text);
			}
		}

	};
    
	public void setVideoPath(String path) {

		Log.d(TAG, "setVideoPath=="+path);
		if(path == null){

					openVideoError();
					return;
				}
				Map<String, String> paramsMap = RequestManager.paseResURI(path);
				
				String id = paramsMap.get("id");
				String provider = paramsMap.get("provider");
				if(id== null){
					id= MOCO_CONSTANTS.ROOT_ID;
				}
				if(provider == null){
					provider = MOCO_CONSTANTS.RECOMMEND_ROOT;
				}
				SonosControler.getInstance(mContext,ServiceMsgDao.getInstance(mContext).getServiceMsgByProvider(provider)).getMediaURI(mContext, id, provider, new SonosListener() {
					
					@Override
					public void onResponse(Object response) {
						try{
							theMp3Path = response.toString();
							setVideoURI(Uri.parse(theMp3Path));
						}catch(Exception e){
							openVideoError();
							Logger.e(TAG, "setVideoURI error on onResponse: "+e.getMessage());
						}
						
					}
					@Override
					public void onError(int err, String msg) {
						openVideoError();
					}
				});
			
		
		
	}
    public  String getMp3Path(){
    	return theMp3Path;
    }
	public void setVideoURI(Uri uri) {
		setVideoURI(uri, null);

	}

	public void setVideoURI(Uri uri, Map<String, String> headers) {
		Logger.d(TAG, "play_url == "+uri);
		mUri = uri;
		mHeaders = headers;
		mSeekWhenPrepared = 0;
		openVideo();
	}

	private void openVideo() {
		if (mUri == null){
			openVideoError();
			return;
		}
        
		Intent i = new Intent("com.android.music.musicservicecommand");
		i.putExtra("command", "pause");
		mContext.sendBroadcast(i);
        
		Log.e("test ples del", "mCurrentState"+mCurrentState);
		release(false);
		try {
			mDuration = -1;
			mCurrentBufferPercentage = 0;
			mMediaPlayer = new MediaPlayer();
			mMediaPlayer.setOnPreparedListener(mPreparedListener);
			mMediaPlayer.setOnCompletionListener(mCompletionListener);
			mMediaPlayer.setOnErrorListener(mErrorListener);
			mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
			mMediaPlayer.setOnInfoListener(mInfoListener);
			mMediaPlayer.setOnSeekCompleteListener(mSeekCompleteListener);
			mMediaPlayer.setOnTimedTextListener(mTimedTextListener);
			
			mMediaPlayer.setDataSource(mContext, mUri, mHeaders);
			mMediaPlayer.setScreenOnWhilePlaying(true);
			mMediaPlayer.prepareAsync();
			mCurrentState = STATE_PREPARING;
		} catch (Exception ex) {
			openVideoError();
			return;
		}
	}

	private void openVideoError() {
		mCurrentState = STATE_ERROR;
		mTargetState = STATE_ERROR;
		mErrorListener.onError(mMediaPlayer,
				MediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
	}

	private void release(boolean cleartargetstate) {
		try {
			if (mMediaPlayer != null) {
				
				
				mMediaPlayer.stop();
				mMediaPlayer.reset();
				mMediaPlayer.release();
				
				mMediaPlayer = null;
				mCurrentState = STATE_IDLE;
				if (cleartargetstate)
					mTargetState = STATE_IDLE;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public void start() {
		try {
			if (isInPlaybackState()) {
				mMediaPlayer.start();
				mCurrentState = STATE_PLAYING;
			}
			mTargetState = STATE_PLAYING;
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void stop() {
		try {
			if (mMediaPlayer != null) {
				mMediaPlayer.stop();
				mMediaPlayer.reset();
				mMediaPlayer.release();
				mMediaPlayer = null;
				mCurrentState = STATE_IDLE;
				mTargetState = STATE_IDLE;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public void pause() {
		try {
			if (isInPlaybackState()) {
				if (mMediaPlayer.isPlaying()) {
					mMediaPlayer.pause();
					mCurrentState = STATE_PAUSED;
				}
			}

			mTargetState = STATE_PAUSED;
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public boolean isPlaying() {
		boolean isPlay = false;
		try {
			if(mMediaPlayer != null){
				isPlay = isInPlaybackState() && mMediaPlayer.isPlaying();	
			}
		} catch (IllegalStateException ex) {
			return isPlay;
		}
		return isPlay;
	}

	@Override
	public int getBufferPercentage() {
		if (mMediaPlayer != null)
			return mCurrentBufferPercentage;
		return 0;
	}

	public void setVolume(float leftVolume, float rightVolume) {
		if (mMediaPlayer != null)
			mMediaPlayer.setVolume(leftVolume, rightVolume);
	}

	protected boolean isInPlaybackState() {
		return (mMediaPlayer != null && mCurrentState != STATE_ERROR
				&& mCurrentState != STATE_IDLE && mCurrentState != STATE_PREPARING);
	}

	@Override
	public void seekTo(long msec) {
		try {
			if (isInPlaybackState()) {

				mMediaPlayer.seekTo((int) msec);
				mSeekWhenPrepared = 0;
			} else {
				mSeekWhenPrepared = msec;
			}
		} catch (Exception e) {

		}
	}

	@Override
	public long getDuration() {
		if (isInPlaybackState()) {
			if (mDuration > 0)
				return mDuration;
			mDuration = mMediaPlayer.getDuration();
			return mDuration;
		}
		mDuration = -1;
		return mDuration;
	}

	@Override
	public long getCurrentPosition() {
		if (isInPlaybackState())
			return mMediaPlayer.getCurrentPosition();
		return 0;
	}

	public void setHardwareDecoder(boolean hardware) {
		mHardwareDecoder = hardware;
	}

	public void setBufferSize(int bufSize) {
		mBufSize = bufSize;
	}

	public boolean isBuffering() {
		if (mMediaPlayer != null)
			return mMediaPlayer.isPlaying();
		return false;
	}

	public int getAudioTrack() {
		if (mMediaPlayer != null)
			return mMediaPlayer.getAudioSessionId();
		return -1;
	}

	public void setAudioTrack(int audioIndex) {
		if (mMediaPlayer != null)
			mMediaPlayer.setAudioSessionId(audioIndex);
	}

	public void setOnPreparedListener(OnPreparedListener l) {
		mOnPreparedListener = l;
	}

	public void setOnCompletionListener(OnCompletionListener l) {
		mOnCompletionListener = l;
	}

	public void setOnErrorListener(OnErrorListener l) {
		mOnErrorListener = l;
	}

	public void setOnBufferingUpdateListener(OnBufferingUpdateListener l) {
		mOnBufferingUpdateListener = l;
	}

	public void setOnSeekCompleteListener(OnSeekCompleteListener l) {
		mOnSeekCompleteListener = l;
	}

	public void setOnTimedTextListener(OnTimedTextListener l) {
		mOnTimedTextListener = l;
	}

	public void setOnInfoListener(OnInfoListener l) {
		mOnInfoListener = l;
	}
}
